package com.sskj.gocoin.v.fragment;


import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.gocoin.LoadingDialog;
import com.sskj.gocoin.R;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.common.rxbus2.NetSubScriber;
import com.sskj.gocoin.m.bean.Currency;
import com.sskj.gocoin.m.bean.bean.NewStock;
import com.sskj.gocoin.p.fragment.MarketFragmentPst;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.GsonUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.RxSchedulersHelper;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.MarketDetailActivity;
import com.sskj.gocoin.v.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

/**
 * 行情列表
 * create by Hey at 2018/5/4 15:33
 */
public class MarketListFragment extends BaseFragment<MainActivity, MarketFragmentPst> {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private BaseAdapter<NewStock> adapter;


    private LoadingDialog dialog;

    private List<NewStock> stockList = new ArrayList<>();

    //type 1侧边栏 0 行情
    private int type = 1;


    private boolean isLoaded;


    @Override
    public void onPause() {
        super.onPause();

    }

    public void update() {
        mPresenter.getData(true);
    }

    /**
     * @param type 0行情 1侧边栏 默认为1
     * @return
     */
    public static MarketListFragment newInstance(int type) {
        Bundle args = new Bundle();
        MarketListFragment fragment = new MarketListFragment();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_list;
    }

    @Override
    public MarketFragmentPst getPresenter() {
        return new MarketFragmentPst();
    }


    public void closeWebSocket() {
        mPresenter.closeWebSocket();
    }

    //    @Subscribe(code = 1,threadMode = ThreadMode.MAIN)
    public void openWebSocket() {
        mPresenter.initWebSocket(type);
    }


    @Override
    public void initView() {
//        RxBus.getDefault().register(this);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }

        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));


        refreshLayout.setOnRefreshListener(refreshLayout1 ->
        {
            refreshLayout.finishRefresh();
            mPresenter.getData(false);
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mActivity, LinearLayoutManager.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.shape_item_decoration));
        recyclerView.addItemDecoration(dividerItemDecoration);
//        recyclerView.setNestedScrollingEnabled(false);
        initAdapter();
    }


    private void initAdapter() {
        adapter = new BaseAdapter<NewStock>(R.layout.recy_item_market, new ArrayList<>(), recyclerView) {
            @Override
            public void bind(ViewHolder injector, NewStock stock) {
                TextView price = injector.getView(R.id.item_price);
                injector.setText(R.id.item_price, "USDT   " + NumberUtil.keepPoint4(stock.getPrice()));
                injector.setText(R.id.item_rmb_price, "≈" + (TextUtils.isEmpty(stock.getCnyPrice()) ? "0.00" : NumberUtil.keep2(stock.getCnyPrice())) + " CNY");
                String name[] = stock.getCode().split("_");
                if (name != null) {
                    injector.setText(R.id.item_type_name, name[0].toUpperCase());
                    if (name.length > 1) {
                        injector.setText(R.id.item_unit, "/" + name[1].toUpperCase());
                    }
                } else {
                    injector.setText(R.id.item_type_name, stock.getName());
                }

                if (stock.getName().toLowerCase().contains("btc")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_btc);
                } else if (stock.getName().toLowerCase().contains("bch")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_bch);
                } else if (stock.getName().toLowerCase().contains("dash")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_dash);
                } else if (stock.getName().toLowerCase().contains("eos")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_eos);
                } else if (stock.getName().toLowerCase().contains("etc")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_etc);
                } else if (stock.getName().toLowerCase().contains("eth")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_eth);
                } else if (stock.getName().toLowerCase().contains("ltc")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_ltc);
                } else if (stock.getName().toLowerCase().contains("kt")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_kt);
                } else if (stock.getName().toLowerCase().contains("zec")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_zec);
                } else if (stock.getName().toLowerCase().contains("xrp")) {
                    injector.setImageResource(R.id.item_type_img, R.mipmap.icon_xrp);
                }

                if (stock.getChange() > 0) {
                    injector.setBackgroundRes(R.id.item_condition_layout, R.drawable.shape_rectangle_green_rc);
                    injector.setText(R.id.item_condition, "+" + stock.getChangeRate());
//                    if (stock.isUpdate()) {
//                        colorAnim(price, true);
//                        stock.setUpdate(false);
//                    }

                } else if (stock.getChange() == 0) {
                    injector.setBackgroundRes(R.id.item_condition_layout, R.drawable.shape_rectangle_gray_rc);
                } else {
                    injector.setBackgroundRes(R.id.item_condition_layout, R.drawable.shape_rectangle_red_rc);
                    injector.setText(R.id.item_condition, stock.getChangeRate());
//                    if (stock.isUpdate()) {
//                        colorAnim(price, false);
//                        stock.setUpdate(false);
//                    }
                }
                if (stock.isUpdate()) {
                    if (stock.isShow()) {
                        Log.i("info", "adapter::" + stock.isShow());
                        colorAnim(price, true);
                        stock.setUpdate(false);
                    } else {
                        Log.i("info", "adapter::" + stock.isShow());
                        colorAnim(price, false);
                        stock.setUpdate(false);
                    }
                }
//                injector.setText(R.id.item_hight_price, String.format(App.INSTANCE.getString(R.string.strMarketListFragment220), stock.getHigh()));
//                injector.setText(R.id.item_low_price, String.format(App.INSTANCE.getString(R.string.strMarketListFragment221), stock.getLow()));

                ClickUtil.click(injector.getView(R.id.market_item), () -> {
                    if (stock.getName().toLowerCase().contains("kt")) {
                        ToastUtil.showShort("该币种暂不支持交易");
                        return;
                    }
                    if (mActivity.mDrawerIsOpen) {
                        mActivity.closeDrawerLayout();
                        mActivity.updateCurrentStock(stock, Currency.BTC);
                        mActivity.upDateFragment(mActivity.index);
                    } else {
                        mActivity.updateCurrentStock(stock, Currency.BTC);
                        MarketDetailActivity.start(getActivity(), stock, 1);
                    }
                });


            }

        };

        adapter.setEmtyView();
    }

    @Override
    public void initData() {
        if (type == 1) {
            mActivity.setOnDrawOpenListener(new MainActivity.onDrawOpenListener() {
                @Override
                public void onOpen() {
                    openWebSocket();
                    mPresenter.getData(isLoaded);
                }

                @Override
                public void onClose() {
//                    closeWebSocket();
                }
            });
        } else {
            mPresenter.getData(false);
        }


    }


    public void loading() {
        LoadingDialog.Builder builder = new LoadingDialog.Builder(getActivity());
        builder.loadText(R.string.loading);
        builder.cancelable(true);
        builder.canceledOnTouchOutside(false);
        dialog = builder.show();
        dialog.show();
    }

    public void stopLoading() {
        if (dialog != null) {
            dialog.cancel();
        }
    }


    public void update(String s) {
        Flowable.just(s)
                .compose(RxSchedulersHelper.transformer())
                .map(s1 -> GsonUtil.GsonToBean(s1, NewStock.class))
                .subscribe(new NetSubScriber<NewStock>() {
                    @Override
                    public void onSuccess(NewStock newStock) {
                        for (int i = 0; i < stockList.size(); i++) {
                            if (stockList.get(i).getCode().equals(newStock.getCode())) {
                                newStock.setUpdate(true);
                                if (TextUtils.isEmpty(newStock.getCnyPrice())) {
                                    newStock.setCnyPrice(stockList.get(i).getCnyPrice());
                                }
                                if (Double.parseDouble(newStock.getPrice()) > Double.parseDouble(stockList.get(i).getPrice())) {  // 当前价高于上一个价格，短暂的涨
                                    newStock.setShow(true);
                                } else if (Double.parseDouble(newStock.getPrice()) < Double.parseDouble(stockList.get(i).getPrice())) {
                                    newStock.setShow(false);
                                } else {
                                    newStock.setUpdate(false);
                                }
                                stockList.set(i, newStock);
                                if (newStock.getName().contains(mActivity.mCurrentStockName)) { //TODO 这里做杠杆交易界面，全球币种 价格刷新
                                    mActivity.mCurrentStock = newStock;
                                    mActivity.upDateLevelFragment();
                                } else if (newStock.getName().contains(mActivity.mTransactionCurrentStockName)) {
                                    mActivity.mTransactionCurrentStock = newStock;
                                }
                            }
                        }
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                    }
                });

    }


    public void setData(List<NewStock> datas) {
        if (datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getChange() > 0) {  // 涨
                    datas.get(i).setShow(true);
                } else {
                    datas.get(i).setShow(false);
                }
            }
            stockList = datas;
            if (!isLoaded) {
                mActivity.mTransactionCurrentStock = stockList.get(0);
                mActivity.mTransactionCurrentStockName = stockList.get(0).getName();
                mActivity.mCurrentStock = stockList.get(0);
                mActivity.mCurrentStockName = stockList.get(0).getName();
            }
            adapter.setNewData(stockList);
            stopLoading();
            isLoaded = true;
            if (type == 0) {
                openWebSocket();
            }
        }
    }


    public void setTextAnim(TextView textView, boolean up) {
        ScaleAnimation scaleAnimation1 = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation1.setDuration(500);
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(1.5f, 1f, 1.4f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation2.setDuration(500);
        scaleAnimation1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                if (up) {
                    textView.setTextColor(getResources().getColor(R.color.market_up));
                } else {
                    textView.setTextColor(getResources().getColor(R.color.market_down));
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                textView.startAnimation(scaleAnimation2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        scaleAnimation2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                textView.setTextColor(getResources().getColor(R.color.market_up));
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        textView.startAnimation(scaleAnimation1);
    }


    public void colorAnim(TextView textView, boolean update) {
        ValueAnimator animator = ValueAnimator.ofFloat(0, 3);
        animator.setDuration(1000);
        animator.setRepeatCount(0);
        animator.addUpdateListener(animation -> {
            float x = (float) animation.getAnimatedValue();
            if (x == 0 && getActivity() != null) {
                textView.setTextColor(update ? getResources().getColor(R.color.market_up) : getResources().getColor(R.color.market_down));
                Log.i("info", "colorAnima:::" + update);
            } else if (x == 3 && getActivity() != null) {
                textView.setTextColor(getResources().getColor(R.color.text_color));
            }
        });
        animator.start();
    }

}
